package com.member.web.controller.shop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.member.common.annotation.Anonymous;
import com.member.common.annotation.Log;
import com.member.common.core.domain.AjaxResult;
import com.member.common.enums.BusinessType;
import com.member.common.utils.StringUtils;
import com.member.common.utils.bean.BeanUtils;
import com.member.shop.domain.SysBizGoods;
import com.member.shop.domain.SysBizGoodsSku;
import com.member.shop.domain.SysBizOrder;
import com.member.shop.domain.SysBizTenant;
import com.member.shop.dto.ErpStockEdit;
import com.member.shop.dto.SysBizTenantExternal;
import com.member.shop.service.ISysBizGoodsService;
import com.member.shop.service.ISysBizGoodsSkuService;
import com.member.shop.service.ISysBizOrderService;
import com.member.shop.service.ISysBizTenantService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.member.common.core.domain.AjaxResult.success;


/*erp 地址同步*/
@Anonymous
@RestController
@RequestMapping("/shop/erp")
public class ErpExternal {


    @Resource
    private ISysBizOrderService sysBizOrderService;
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;

    @Resource
    private ISysBizGoodsService sysBizGoodsService;

    @Resource
    private ISysBizTenantService sysBizTenantService;

    /**
     * 商品库存变动接口
     */
    @Log(title = "商品库存变动接口", businessType = BusinessType.UPDATE)
    @PutMapping("/stockEdit")
    public AjaxResult stockEdit(@RequestBody List<ErpStockEdit> erpStockEdits) {
        try {
            // 参数校验
            if (CollectionUtils.isEmpty(erpStockEdits)) {
                return AjaxResult.error("商品库存变动列表不能为空");
            }
            if (erpStockEdits.size() > 100) {
                return AjaxResult.error("商品库存变动列表不能超过100个");
            }
            for (ErpStockEdit erpStockEdit : erpStockEdits) {
                if (erpStockEdit == null) {
                    return AjaxResult.error("请求项为空");
                }
                if (StringUtils.isEmpty(erpStockEdit.getProductCode())) {
                    return AjaxResult.error("商品编码不能为空");
                }
                if (erpStockEdit.getStock() == null) {
                    return AjaxResult.error("商品库存不能为空");
                }
            }
            List<String> errorMessages = new ArrayList<>();
            List<SysBizGoods> ordersToUpdate = new ArrayList<SysBizGoods>();

            for (ErpStockEdit erpStockEdit : erpStockEdits) {
                // 使用for循环来查询每个商品编码对应的SysBizGoodsSku
                List<SysBizGoodsSku> sysBizGoodsSkus = sysBizGoodsSkuService.selectSysBizGoodsSkuList(new LambdaQueryWrapper<SysBizGoodsSku>()
                        .eq(SysBizGoodsSku::getErpProductCode, erpStockEdit.getProductCode()));

                if (CollectionUtils.isEmpty(sysBizGoodsSkus)) {
                    errorMessages.add(erpStockEdit.getProductCode());
                    continue;
                }

                // 假设业务上同一ERP商品编码只对应一个sku，否则需要根据具体业务逻辑调整
                SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkus.get(0);

                //通过sku 找到对应的商品
                Long goodsId = sysBizGoodsSku.getGoodsId();
                SysBizGoods goods = sysBizGoodsService.getById(goodsId);

                if (goods == null) {
                    errorMessages.add(erpStockEdit.getProductCode());
                    continue;
                }

                // 更新商品库存 （减少）
                if (erpStockEdit.getStock() < 0) {
                    // 更新冻结库存
                    goods.setFrozenStockCount(goods.getFrozenStockCount() + Math.abs(erpStockEdit.getStock()));
                    if (goods.getFrozenStockCount() >= goods.getStock()) {
                        goods.setFrozenStockCount(goods.getStock());
                    }
                    ordersToUpdate.add(goods);
                } else if (erpStockEdit.getStock() > 0) {
                    // 更新商品总库存
                    goods.setStock(erpStockEdit.getStock() + goods.getStock());
                    goods.setInventoryStock(erpStockEdit.getStock() + goods.getInventoryStock());
                    ordersToUpdate.add(goods);
                }
            }
            if (ordersToUpdate.isEmpty()) {
                return AjaxResult.error("没有有效的商品库存变动请求");
            }

            // 批量更新库存
            boolean updateSuccess = sysBizGoodsService.updateBatchById(ordersToUpdate);
            if (!updateSuccess) {
                return AjaxResult.error("更新库存失败");
            }
            if (!errorMessages.isEmpty()) {
                return AjaxResult.warn("部分商品库存变动失败", errorMessages);
            }
            return success("更新库存成功");
        } catch (Exception e) {
            return AjaxResult.error("系统异常，请稍后再试");
        }
    }


    /**
     * 20-30，由ERP调用接口更新发货状态。
     */
    @Log(title = "ERP调用接口更新发货状态", businessType = BusinessType.UPDATE)
    @PutMapping("/sendStatus")
    public AjaxResult updateSendStatus(@RequestBody List<String> orderCodes) {
        try {
            // 参数校验
            if (CollectionUtils.isEmpty(orderCodes)) {
                return AjaxResult.error("订单号列表不能为空");
            }
            if (orderCodes.size() > 100) {
                return AjaxResult.error("订单号列表不能超过100个");
            }
            for (String erpStockEdit : orderCodes) {
                if (StringUtils.isEmpty(erpStockEdit)) {
                    return AjaxResult.error("订单号不能为空");
                }
            }
            // 检查订单状态并更新
            List<SysBizOrder> ordersToUpdate = new ArrayList<>();
            List<String> errorOrderCodes = new ArrayList<>();
            for (String erpStockEdit : orderCodes) {
                SysBizOrder sysBizOrder = sysBizOrderService.getOne(new LambdaQueryWrapper<SysBizOrder>().eq(SysBizOrder::getOrderCode, erpStockEdit));
                if (sysBizOrder == null || sysBizOrder.getStatus() != 20) {
                    errorOrderCodes.add(erpStockEdit);
                } else {
                    sysBizOrder.setStatus(30);
                    ordersToUpdate.add(sysBizOrder);
                }
            }
            if (ordersToUpdate.isEmpty()) {
                return AjaxResult.error("没有有效的订单发货请求");
            }
            // 批量更新订单状态
            boolean updateSuccess = sysBizOrderService.updateBatchById(ordersToUpdate);

            if (!updateSuccess) {
                return AjaxResult.error("更新发货状态失败");
            }
            if (!errorOrderCodes.isEmpty()) {
                return AjaxResult.warn("部分订单状态更新失败", errorOrderCodes);
            }
            return success("更新发货状态成功");

        } catch (Exception e) {
            return AjaxResult.error("系统异常，请稍后再试");
        }
    }


    /**
     * 30-40 ，由ERP调用接口更新已完成状态。
     */
    @Log(title = "ERP调用接口更新已完成状态", businessType = BusinessType.UPDATE)
    @PutMapping("/complete")
    public AjaxResult complete(@RequestBody List<String> orderCodes) {
        try {
            // 参数校验
            if (CollectionUtils.isEmpty(orderCodes)) {
                return AjaxResult.error("订单号列表不能为空");
            }
            if (orderCodes.size() > 100) {
                return AjaxResult.error("订单号列表不能超过100个");
            }
            for (String erpStockEdit : orderCodes) {
                if (StringUtils.isEmpty(erpStockEdit)) {
                    return AjaxResult.error("订单号不能为空");
                }
            }

            // 检查订单状态并更新
            List<SysBizOrder> ordersToUpdate = new ArrayList<>();
            List<String> errorOrderCodes = new ArrayList<>();

            for (String erpStockEdit : orderCodes) {
                SysBizOrder sysBizOrder = sysBizOrderService.getOne(new LambdaQueryWrapper<SysBizOrder>().eq(SysBizOrder::getOrderCode, erpStockEdit));
                if (sysBizOrder == null || sysBizOrder.getStatus() != 30) {
                    errorOrderCodes.add(erpStockEdit);
                } else {
                    sysBizOrder.setStatus(40);
                    ordersToUpdate.add(sysBizOrder);
                }
            }

            if (ordersToUpdate.isEmpty()) {
                return AjaxResult.error("没有有效的订单发货请求");
            }

            // 批量更新订单状态
            boolean updateSuccess = sysBizOrderService.updateBatchById(ordersToUpdate);

            if (!updateSuccess) {
                return AjaxResult.error("更新已完成状态失败");
            }
            if (!errorOrderCodes.isEmpty()) {
                return AjaxResult.warn("部分订单状态更新失败 ", errorOrderCodes);
            }
            return success("更新已完成状态成功");

        } catch (Exception e) {
            return AjaxResult.error("系统异常，请稍后再试");
        }
    }


    /**
     * 根据站点Id获取站点信息
     */
    @Log(title = " 根据站点Id获取站点信息", businessType = BusinessType.UPDATE)
    @RequestMapping("/getTenantInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        if (id==null) {
            return AjaxResult.error("id不能为空");
        }
        SysBizTenant sysBizTenant = sysBizTenantService.selectSysBizTenantById(id);
        SysBizTenantExternal sysBizTenantExternal = new SysBizTenantExternal();
        BeanUtils.copyProperties(sysBizTenant, sysBizTenantExternal);
        return success(sysBizTenantExternal);
    }
}
